package mrkj.keepfit.utils;

import android.text.TextUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 下载数据的工具类
 */
public class HttpUtils {
	private static String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
	private static final int DEF_CONN_TIMEOUT = 30000;
	private static final int DEF_READ_TIMEOUT = 30000;
	private static final String DEF_CHATSET = "UTF-8";

	/**
	 * HttpUrl 通用数据获取
	 */
	public static String getJsonStr(String dataUrl) {
		HttpURLConnection connection = null;
		BufferedReader reader = null;
		String rs = null;
		try {
			StringBuffer sb = new StringBuffer();
			URL url = new URL(dataUrl);
			connection = (HttpURLConnection) url.openConnection();
			connection.setRequestProperty("User-agent", userAgent);
			connection.setUseCaches(false);
			connection.setConnectTimeout(DEF_CONN_TIMEOUT);
			connection.setReadTimeout(DEF_READ_TIMEOUT);
			connection.setInstanceFollowRedirects(false);
			connection.setRequestMethod("GET");
			connection.connect();

			if (connection.getResponseCode() == 200) {
				InputStream is = connection.getInputStream();
				reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
				String strRead;
				while ((strRead = reader.readLine()) != null) {
					sb.append(strRead);
				}
				rs = sb.toString();
				return rs;
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (connection != null) {
				connection.disconnect();
			}
		}
		return null;
	}
}